/**
 * Copyright: Copyright (c)2011
 * Company: 易宝支付(YeePay)
 */
package net.loyintean.pearlshell.base.service.impl;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;

import net.loyintean.pearlshell.base.model.ILogInfo;
import net.loyintean.pearlshell.base.model.impl.LogInfoFactory;
import net.loyintean.pearlshell.base.service.HttpParseService;

import org.apache.commons.httpclient.methods.EntityEnclosingMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.log4j.Logger;

/** 请求数据生成器
 * <p>
 * 
 * @author：jun.lin@yeepay.com
 * @since：2015年4月5日 下午9:51:22
 * @version: */
public abstract class RequestEntityGenerater<T, E> implements
		HttpParseService<T, E> {

	private static final Logger LOGGER = Logger
			.getLogger(RequestEntityGenerater.class);

	/** charset :编码格式
	 * <p>
	 * 默认为UT-8 */
	private String charset = "UTF-8";

	private HttpParseService<T, E> customerParser;

	/** 将请求分发给合适的处理器
	 * <p>
	 * 
	 * @see net.loyintean.pearlshell.base.service.HttpParseService
	 *      #generateRequestEntity(java.lang.Object) */
	@Override
	public void generateRequestEntity(T param, EntityEnclosingMethod method)
			throws IOException {
		assert param != null;

		ILogInfo logInfo = LogInfoFactory.BUILD("param=" + param);
		LOGGER.info(logInfo.start());

		// File,String,MultiPart
		RequestEntity entity = null;
		if (param instanceof String) {
			try {
				entity = new StringRequestEntity((String) param, "text/html;",
						charset);
			} catch (UnsupportedEncodingException e) {
				LOGGER.error(logInfo.error(e.getMessage()), e);
				throw e;
			}
		} else if (param instanceof Map) {

			Map<?, ?> paramMap = (Map<?, ?>) param;
			for (Object paramKey : paramMap.keySet()) {

			}

		} else if (customerParser == null) {

		} else {
			entity = customerParser.generateRequestEntity(param);
		}

		LOGGER.info(logInfo.end("the RequestEntity =" + entity));
		return entity;
	}

	/** @param charset
	 *            the charset to set */
	protected void setCharset(String charset) {
		this.charset = charset;
	}

	/** @param customerParser
	 *            the customerParser to set */
	protected void setCustomerParser(HttpParseService<T, E> customerParser) {
		this.customerParser = customerParser;
	}
}
